#!/usr/bin/perl

use Cwd;

$baseurl = getcwd;


if ($ARGV[0] eq 'CREATING') {
    $mode = 'CREATING';
} else {
    $mode = 'UPDATING';
}

print 'ARGV[1]: ' . $ARGV[1] . "\n";

if ($ARGV[1] =~ /\//) {
    ($baseurl = $ARGV[1]) =~ s/[\/]*$//;
}

$error_outs = $baseurl . '/universal_identifiers_errors.txt';
$print_outs = $baseurl . '/universal_identifiers_prints.txt';

binmode(STDOUT, ':utf8');

open (STDERR, ">$error_outs");
open (STDOUT, ">$print_outs");

print "baseurl: " . $baseurl . "\n";

# local system variables
$connect = $baseurl . '/connect.pl';
require $connect;

#THIS SCRIPT HAS TO BE RUN FOR III CATALOGS, BECAUSE THE OCLC NUMBERS ARE EXPORTED INCORRECTLY IN A NUMBER OF CASES.
#
#THE ONLY WAY TO GET ACCURATE OCLC NUMBERS IS TO PRINT THEM IN A LIST, RATHER THAN EXPORT THEM.
#
#NOTE: IN ORDER TO USE THIS SCRIPT, YOU MUST FIRST QUERY A SET OF ALL BIB RECORDS

#THEN YOU MUST "EXPORT" INFORMATION FROM CATALOG
#for instance:

#   RECORD #(BIBLIO)    OCLC #

#THE RESULTING TEXT FILE NEEDS TO BE LOADED INTO ./universal_ids/

use IO::File;

($HOUR, $MIN, $SEC) = (localtime)[2, 1, 0];
$start_time = "$HOUR:$MIN:$SEC";

$where = $baseurl . '/universal_ids';

while (defined($next_file = <$where/*.out>)) {

#print $next_file . "\n";

    open(IN, "< $next_file") || die "cannot open $next_file for reading: $!";

$batch_textfiles = $next_file;
$batch_textfiles =~ s/universal_ids/universal_ids_textfiles/g;

$batch_loader = IO::File->new("> $batch_textfiles") || die "cannot open $batch_textfiles for writing: $!\n";
flock($batch_loader, 2);

    open(IN, "< $next_file") || die "cannot open $next_file for reading: $!";

        while(<IN>) {

        if($_ !~ /^RECORD #\(BIBLIO\)/) {
            $_ =~ s/\n//;
            @fields = split(/\t/);

            $fields[1] =~ s/^[ ]*|[ ]*$//;

                %query_insert = (
                    local_control_number => '',
                    true_oclc => '',
                    universal_identifier => ''
                );

                $query_insert{'local_control_number'} = $institution . substr($fields[0], 0, 8);
                $query_insert{'true_oclc'} = $fields[1];

                if($fields[1] =~ /^[0-9]{1,8}$/) {
                    $oclc_length = 8 - length($fields[1]);
                    $query_insert{'universal_identifier'} = 'ocm' . 0 x $oclc_length  . $fields[1];
                } elsif($fields[1] =~ /^[0-9]{1,9}$/) {
                    $query_insert{'universal_identifier'} = 'ocn' . $fields[1];
                } elsif($fields[1] =~ /^[0-9]{8}agr$/) {
                    $query_insert{'universal_identifier'} = $fields[1];
                } else {
                    $query_insert{'universal_identifier'} = $query_insert{'local_control_number'} . '_' . $fields[1];
                }

                @keys = keys %query_insert;
                @values = values %query_insert;

                $mysql_keys = join(", ", @keys);
                $mysql_values = join("\t", @values);
                $mysql_values =~ s/\\\t/\\ \t/g;

                print $batch_loader $mysql_values . "\n";

                undef(%query_insert);

        }
    }

                undef(@keys);
                undef(@values);

    close(IN) || "cannot close $next_file: $!";

unlink($next_file);

    $batch_loader->autoflush(1);
    close($batch_loader, 2) || "cannot close $batch_loader: $!";

}

($HOUR, $MIN, $SEC) = (localtime)[2, 1, 0];
$end_of_file_creation_time = "$HOUR:$MIN:$SEC";

#print $mysql_keys . "\n";

use DBI;

# connection for the select
$dbh = DBI->connect("DBI:mysql:database=$db_name;host=$db_host", $db_user, $db_pass, { mysql_enable_utf8 =>1 }) or die "couldn't connect to database: " . DBI->errstr;

$this_table = $institution . '_universal_ids';

$sth = $dbh->do("TRUNCATE TABLE $this_table");

    $querystring = "SHOW FIELDS FROM $this_table";

        $query = $dbh->prepare($querystring)
            or die("couldn't prepare statement: ". $dbh->errstr);

        $query->execute()
            or die("couldn't execute statement: ". $dbh->errstr);

    while ( @row = $query->fetchrow_array ) {
        push (@keys, $row[0]); ## field name
    }

$query->finish();

pop(@keys);

$mysql_keys = join(", ", @keys);

$where = $baseurl . '/universal_ids_textfiles';

while (defined($next_file = <$where/*.out>)) {

    $sth2 = $dbh->do("LOAD DATA INFILE '" . $next_file . "' REPLACE INTO TABLE $this_table FIELDS TERMINATED BY '\t' (" . $mysql_keys . ")");

unlink($next_file);

}

$dbh->disconnect;

($HOUR, $MIN, $SEC) = (localtime)[2, 1, 0];
$end_time = "$HOUR:$MIN:$SEC";

print "Start time: " . $start_time . "\nEnd of file creation time: " . $end_of_file_creation_time . "\nEnd time: " . $end_time . "\n";


